package sto.android.app;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.device.ScanManager;
import android.device.scanner.configuration.Triggering;
import android.util.Log;

/**
 * urovo扫描帮助类，构造方法中放入扫描监听 
 * 页面加载时, 调用registerScanReceiver注册扫描 
 * 页面暂停时, 调用unregisterScanReceiver卸载扫描
 */
public class UrovoScan {
	private final static String SCAN_ACTION = "urovo.rcv.message";
	private String barcodeStr;

	// 是否正在扫描
	private boolean isScanning = false;
	// 扫描管理对象
	private ScanManager mScanManager = new ScanManager();
	// 是否连续扫描
	public boolean isContinuousMode = false;
	// 未扫描到条码计数器
	private int notScannedCounter = 0;
	// 未扫到条码自动停止数量
	private final int AUTO_STOP_MAX_COUNT = 100;
	// 连续扫描线程
	private AutoScanThread autoScanThread = null;
	// 条码重复次数
	private int repeatCount = 0;



	public UrovoScan() {

	}

	public UrovoScan(ScanListener scanListener) {
		this.scanListener = scanListener;
	}

	/**
	 * 初始化扫描头
	 */
	public void openScanner() {
		try {
			boolean scanPowerState = mScanManager.getScannerState();
			if (!scanPowerState) {
				mScanManager.openScanner();
			}
			boolean lockTrigglerState = mScanManager.getTriggerLockState();
			if (!lockTrigglerState) {
				mScanManager.unlockTriggler();
			}
			// 设置输出模式，0为广播模式，1为键盘输出模式
			mScanManager.switchOutputMode(0);
			// 将扫描模式设置为非连续扫描，否则如果开起了系统的连续扫描模式，在启动自定义连续扫描时会导致系统不断重启
			mScanManager.setTriggerMode(Triggering.HOST);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 切换扫描模式
	 */
	public void switchTriggerMode() {
		try {
			if (isContinuousMode) {
				stopContinueScan();
			} else {
				notScannedCounter = 0;
				isContinuousMode = true;

				autoScanThread = new AutoScanThread();
				autoScanThread.start();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	class AutoScanThread extends Thread {
		public void run() {
			while (!(isInterrupted())) {
				while (isContinuousMode) {
					try {
						if (isScanning) {
							Thread.sleep(100L);
							continue;
						}

						Thread.sleep(100L);
						mScanManager.startDecode();
						Thread.sleep(600L);

						notScannedCounter++;
						if (notScannedCounter > AUTO_STOP_MAX_COUNT) {
							stopContinueScan();
						}
					} catch (Exception e) {
						e.printStackTrace();
					} finally {
						mScanManager.stopDecode();
					}
				}
				interrupt();
			}
		}
	}

	/**
	 * 停止连续扫描
	 */
	public void stopContinueScan() {
		isContinuousMode = false;
		notScannedCounter = 0;

		mScanManager.stopDecode();
		try {
			Thread.sleep(0);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		Log.d("[BroadcastReceiver]", "连续扫描停止");
	}

	/**
	 * 关闭扫描头
	 */
	public void closeScanner() {
		if (mScanManager != null) {
			mScanManager.stopDecode();
		}

		boolean lockTrigglerState = mScanManager.getTriggerLockState();
		if (mScanManager != null && lockTrigglerState) {
			mScanManager.lockTriggler();
		}

		boolean scanPowerState = mScanManager.getScannerState();
		if (mScanManager != null && !scanPowerState) {
			mScanManager.closeScanner();
		}
	}

	/**
	 * 扫描接受器
	 */
	private BroadcastReceiver mScanReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			isScanning = true;
			byte[] barocode = intent.getByteArrayExtra("barocode");
			int barocodelen = intent.getIntExtra("length", 0);
			String tempBarcode = new String(barocode, 0, barocodelen);
			Log.d("[BroadcastReceiver]", tempBarcode);
			if (isContinuousMode) {
				if (tempBarcode.equals(getLastScanResult())) {
					repeatCount++;
					if (repeatCount > 2) {
						repeatCount = 0;
						barcodeStr = tempBarcode;
						scanListener.onScan(barcodeStr);
					}
				} else {
					repeatCount = 0;
					barcodeStr = tempBarcode;
					scanListener.onScan(barcodeStr);
				}
			} else {
				repeatCount = 0;
				barcodeStr = tempBarcode;
				scanListener.onScan(barcodeStr);
			}
			notScannedCounter = 0;
			isScanning = false;
		}
	};

	/**
	 * 获取最后一次扫描结果
	 */
	public String getLastScanResult() {
		return barcodeStr;
	}

	/**
	 * 注册扫描
	 */
	public void registerScanReceiver(Context context) {
		IntentFilter filter = new IntentFilter();
		filter.addAction(SCAN_ACTION);
		context.registerReceiver(mScanReceiver, filter);
	}

	/**
	 * 卸载扫描
	 */
	public void unregisterScanReceiver(Context context) {
		context.unregisterReceiver(mScanReceiver);
	}

	private ScanListener scanListener;

	public interface ScanListener {
		/**
		 * 扫描到内容后回调此方法
		 * 
		 * @param barcode
		 */
		public void onScan(String barcode);
	}
}
